package com.atguigu.gmall.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @author: atguigu
 * @create: 2023-08-03 10:24
 */
@Controller
public class IndexController {


    @Autowired
    private ProductFeignClient productFeignClient;

    /***
     * 渲染首页
     * @param model
     * @return
     */
    @GetMapping({"/", "", "/index.html"})
    public String indexHtml(Model model) {
        //1.远程调用商品服务获取首页需要分类数据
        List<JSONObject> list = productFeignClient.getBaseCategoryList();
        model.addAttribute("list", list);

        //2.todo 调用广告服务获取广告列表

        //3.todo 调用推荐服务获取推荐商品

        //4.todo 调用运营服务获取热卖商品/新品等  如果有多项数据获取改串行为并行提交效率
        return "/index/index";
    }


    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 生成首页静态文件
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/create")
    public Result createIndexHtmlFile() {
        try {
            //1.远程调用商品服务获取首页需要分类数据
            List<JSONObject> list = productFeignClient.getBaseCategoryList();
            //2.创建上下文对象封装页面数据模型
            Context context = new Context();
            context.setVariable("list", list);
            //3.创建写文件对象
            String filePath = "D:\\tmp\\index.html";
            FileWriter fileWriter = new FileWriter(filePath);
            //4.调用模板引擎方法生成静态文件
            templateEngine.process("/index/index", context, fileWriter);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.ok();
    }
}
